# ~*~ coding: utf-8 ~*~
import time
from apps.extensions import cache


class Connectivity:
    UNREACHABLE, REACHABLE, UNKNOWN = range(0, 3)
    CONNECTIVITY_CHOICES = (
        (UNREACHABLE, "Unreachable"),
        (REACHABLE, 'Reachable'),
        (UNKNOWN, "Unknown"),
    )

    status = UNKNOWN
    datetime = time.time()

    def __init__(self, status, datetime):
        self.status = status
        self.datetime = datetime

    def display(self):
        return dict(self.__class__.CONNECTIVITY_CHOICES).get(self.status)

    def is_reachable(self):
        return self.status == self.REACHABLE

    def is_unreachable(self):
        return self.status == self.UNREACHABLE

    def is_unknown(self):
        return self.status == self.UNKNOWN

    @classmethod
    def unreachable(cls):
        return cls(cls.UNREACHABLE, time.time())

    @classmethod
    def reachable(cls):
        return cls(cls.REACHABLE, time.time())

    @classmethod
    def unknown(cls):
        return cls(cls.UNKNOWN, time.time())

    @classmethod
    def set(cls, key, value, ttl=0):
        cache.set(key, value, ttl)

    @classmethod
    def get(cls, key):
        value = cache.get(key)
        if not isinstance(value, cls):
            value = cls.unknown()
        return value

    @classmethod
    def set_unreachable(cls, key, ttl=0):
        cls.set(key, cls.unreachable(), ttl)

    @classmethod
    def set_reachable(cls, key, ttl=0):
        cls.set(key, cls.reachable(), ttl)

    def __eq__(self, other):
        return self.status == other.status

    def __gt__(self, other):
        return self.status > other.status

    def __lt__(self, other):
        return not self.__gt__(other)

    def __str__(self):
        return self.display()
